import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const ErrandSchema = new mongoose.Schema({
    fromPlace: String,
    toPlace: String,
    createTime: Number,
    startTime: Number,
    endTime: Number,
    tel: String,
    desc: String, // 跑腿是描述；帮帮忙是服务类型
    note: String,
    imgs: Array, // 上架货号等图片
    idImgs: Array, // 有效证件
    gender: String, // 服务要求，男女
    price: Number,
    type: Number, // 类型，0跑腿或者1帮帮忙
    creatorId: String,
    creator: Object,
    getterId: String,
    getter: Object,
    status: Number, // 0 待支付，1 已支付, 2 被抢单, 2.5 跑手确认, 3 已完成(发布者确认), -1 已取消
    isCreatorCmt: Boolean,
    creatorMsg: String,
    isGetterCmt: Boolean,
    getterMsg: String,
    schoolId: String, // 所属学校
});

ErrandSchema.methods.saveErrand = function (errand, cb) {
    errand.createTime = moment().unix();
    errand.isCreatorCmt = false;
    errand.isGetterCmt = false;
    this.model('errand').insertMany([errand], cb);
};

ErrandSchema.methods.getErrands = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    if (leftQuery.createTime) {
        leftQuery.createTime = { $lt: leftQuery.createTime }
    }
    const errandModel = this.model('errand');
    errandModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        errandModel.find(leftQuery).skip((current - 1) * pageSize).limit(pageSize).exec((err, errands) => cb(err, errands, count, hasMore));
    });
};

ErrandSchema.methods.getAllErrands = function (query, cb) {
    // this.model('errand').find(query, { name: 1, _id: 0 }, cb);
    this.model('errand').find(query, cb);
};

ErrandSchema.methods.getErrand = function (query, cb) {
    this.model('errand').findOne(query, cb);
};

ErrandSchema.methods.updateErrand = function (errand, cb) {
    const _id = errand._id;
    delete errand._id;
    this.model('errand').findOneAndUpdate({ _id }, { $set: errand }, cb);
};

ErrandSchema.methods.removeErrands = function (errandIds, cb) {
    this.model('errand').remove({ _id: { $in: errandIds } }, cb);
};

export default db.model('errand', ErrandSchema);